package com.fly.core.log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.io.IOUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import com.fly.core.utils.SpringContextUtils;

/**
 * 日志数据源注入，注意不能依赖web事件
 */
@Component
public class Log4j2Configuration implements ApplicationListener<ContextRefreshedEvent>
{
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)
    {
        try
        {
            if (ResourceUtils.isFileURL(ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX)))
            {
                // 通过properties文件传递日志数据源配置
                String path = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath() + "jdbc-log.properties";
                Collection<String> lines = new ArrayList<>();
                lines.add("druid.url=" + SpringContextUtils.getProperty("jdbc.url"));
                lines.add("druid.username=" + SpringContextUtils.getProperty("jdbc.username"));
                lines.add("druid.password=" + SpringContextUtils.getProperty("jdbc.password"));
                lines.add("druid.driverClassName=" + SpringContextUtils.getProperty("jdbc.driverClassName"));
                try (OutputStream outputStream = new FileOutputStream(new File(path)))
                {
                    IOUtils.writeLines(lines, null, outputStream, StandardCharsets.UTF_8);
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}